<?php
/**
 * 商场任务管理
 * @author ice<iceinto@mallog.com.cn>
 */
class TaskManageAction extends CommonAction
{
    public function _initialize()
    {
        $this->assign('nav', 3);
        parent::_initialize();
    }

    /**
     * 任务列表
     *
     * @author ice<iceinto@mallog.com.cn>
     */
    public function index()
    {
        $taskAudit = D('MallSetting')->getSettingValue($this->_mid, 'task_audit');
        $count = 0;
        if ($taskAudit) {
            $count = D('Task')->getStatusCount(3, 0, $this->_mid);
        }
        $this->assign('taskMallAutoCount', intval($count));
        $this->assign('taskMallAuto', $taskAudit);
        $this->display();
    }

    /**
     * 任务添加
     * 创建任务要满足
     *
     * @author ice<iceinto@mallog.com.cn>
     */
    public function add()
    {
        $status = 1;
        $mall = $this->getGetData();
        foreach ($mall as $k => $v) {
            if (!$v) {
                $status = 0;
                $this->ajaxReturn('数据不对', null, $status);
            } else {
                $this->assign($k, $v);
            }
        }
        //授权
        $this->ajaxIsAuthorize($mall['mid'], $mall['fid'], $mall['bid']);
        //数据判断
        $TaskModel = D('Task');
        $activity = $TaskModel->getBrandCurrentActivity($mall['mid'], $mall['fid'], $mall['bid']);
        if ($activity) {
            if ($activity['status'] != 100) {
                $status = 0;
                $this->ajaxReturn('你现在还不能添加活动，因为已经有个活动没有处理完成', null, $status);
            }
        }
        // 获取地点信息
        if (isPost()) {
            //TODO 添加任务过程 判断只有在没有任务和任务为推送完成的情况下可以添加
            $TaskModel = M('Task');
            $data = $this->getPost();
            if (true) {
                //获取是否需要审核配置
                $taskAudit = D('MallSetting')->getSettingValue($mall['mid'], 'task_audit');
                if ($taskAudit) {
                    $data['status'] = 3;
                }
                if ($TaskModel->add($data)) {
                    $status = 1;
                    $this->ajaxReturn(L('_ADD_SUCCESS') . '，刷新后显示', null, $status);
                } else {
                    $status = 0;
                    $this->ajaxReturn(L('_ADD_LOSE'), null, $status);
                }
            }
        }
        $phones = D('MallPhone')->getList($mall['mid'], $mall['fid'], $mall['bid']);
        $task = D('Mall')->setAddress($mall);
        $this->assign('phones', $phones);
        $this->assign('task', $task);
        $this->ajaxReturn($this->fetch(), null, $status);
    }

    /**
     * 任务修改
     * 在任务进行的过程中任务不可以修改
     *
     * @author ice<iceinto@mallog.com.cn>
     */
    public function update()
    {
        $status = 0;
        $id = getGetOrPost('id');

        $TaskModel = D('Task');
        $TaskVersionModel = D('TaskVersion');
        $MallModel = D('Mall');
        $TaskReturnModel = D('TaskReturn');
        $TaskAllotModel = D('TaskAllot');
        $UserModel = D('User');
        $QueueModel = D('Queue');

        $returns = array();
        $allot = array();

        $task = $TaskModel->find($id);
        if (!$task) {
            $this->error(L('_ID_ERROR'));
        }
        //授权
        $this->ajaxIsAuthorize($task['mid'], $task['fid'], $task['bid']);
        $phones = D('MallPhone')->getList($task['mid'], $task['fid'], $task['bid']);
        $this->assign('phones', $phones);
        // Obtain state
        $queueStatus = intval($QueueModel->getStatusById($id));
        $task ['queue_status'] = $queueStatus ? $queueStatus : 1;
        $task ['status_info'] = $QueueModel->getStatus($task ['queue_status']);
        // Get in the store floor brand information
        $task = $MallModel->setAddress($task);
        // Judge state to deal with and be returned state can be modified
        if ($task ['queue_status'] == 1 || $task ['queue_status'] == 4) {
            if ($task ['queue_status'] == 4) {
                // Get return information
                $returns = $TaskReturnModel->getReturn($id);
                // Get task allot
                $allot = $TaskAllotModel->getOneByTid($id);
                $this->assign('allot', $allot);
                $this->assign('returns', $returns);
            }
        } else {
            $this->detail($task);
            exit ();
        }
        // 获取当前版本号
        // $version = $TaskVersionModel->getVersion($id);
        $version = $task ['version'];
        if (isPost()) {
            $data = $this->getPost(true);
            if ($this->autoCheckToken()) {
                $data ['id'] = $id;
                $data ['version'] = $version + 1;
                if ($TaskModel->save($data)) {
                    $task ['version'] = $version;
                    $TaskVersionModel->addOne($task);
                    // Update queue
                    $QueueModel->updateStatus($id, 5); // '需求退回已经处理'
                    // Update return
                    if ($returns) {
                        foreach ($returns as $return) {
                            unset ($data);
                            $data ['id'] = $return ['id'];
                            $data ['reply'] = hh(getPost('remark'));
                            $data ['reply_time'] = time();
                            $TaskReturnModel->save($data);
                            $TaskReturnModel->updateStatus($return ['id'], 2); // 解决问题
                        }
                    }
                    $status = 1;
                    $this->ajaxReturn(L('_UPDATE_SUCCESS'), null, $status);
                } else {
                    $status = 0;
                    $this->ajaxReturn(L('_UPDATE_LOSE'), null, $status);
                }
            }
        }
        $this->assign('task', $task);
        $this->ajaxReturn($this->fetch(), null, 1);
    }

    /**
     * 任务详细
     * 可以看到当前任务状态，如果任务在开始和完成的状态可以看到完成人
     *
     * @author ice<iceinto@mallog.com.cn>
     */
    public function detail($task)
    {
        // According to different state with detailed
        $TaskAllotModel = D('TaskAllot');
        if ($task ['status'] == 2) {
            $task ['num'] = $TaskAllotModel->getUserNum($task ['id']);
        }
        $this->assign('task', $task);
        $this->ajaxReturn($this->view->fetch('detail'), null, 1);
    }

    /**
     * 获取客户端提交参数
     *
     * @author ice<iceinto@mallog.com.cn>
     */
    public function getPost($isEdit = false)
    {
        $data = array();
        $status = 0;
        $uid = $this->getLoginUserInfo();
        $data ['uid'] = $uid;
        $data ['title'] = hh(getPost('title'));
        $data ['keyword'] = hh(getPost('keyword'));
        $data ['start_time'] = strtotime(getPost('start_time'));
        $data ['end_time'] = strtotime(getPost('end_time'));
        $data ['content'] = hh(getPost('content'));
        $data ['remark'] = hh(getPost('remark'));
        //$data ['slider'] = intval ( getPost ( 'slider' ) );
        if (!$data ['start_time']) {
            $this->ajaxReturn('开始时间必须', null, $status);
        }
        if (!$data ['end_time']) {
            $this->ajaxReturn('结束时间必须', null, $status);
        }
        if ($data ['start_time'] > $data ['end_time']) {
            $this->ajaxReturn('开始时间不能大于结束时间', null, $status);
        }
        if ($isEdit) {
            $data ['update_time'] = time();
        } else {
            // 获取商场楼层品牌
            $data ['fid'] = intval(getPost('fid'));
            $data ['mid'] = intval(getPost('mid'));
            $data ['bid'] = intval(getPost('bid'));
            $data ['create_time'] = time();
            if (!$data ['fid']) {
                $this->ajaxReturn(L('_FLOOR_MUST'), null, $status);
            }
            if (!$data ['mid']) {
                $this->ajaxReturn(L('_MARKET_MUST'), null, $status);
            }
            if (!$data ['bid']) {
                $this->ajaxReturn(L('_BRAND_MUST'), null, $status);
            }
        }
        // 判断条件必须
        if (!$data ['title']) {
            $this->ajaxReturn(L('_TITLE'), null, $status);
        }
        if (!$data ['keyword']) {
            $this->ajaxReturn(L('_KEYWORD'), null, $status);
        }
        return $data;
    }

    /**
     * 获取客户端提交参数
     *
     * @author ice<iceinto@mallog.com.cn>
     */
    public function getGetData()
    {
        $data ['fid'] = intval(getGetOrPost('fid'));
        $data ['mid'] = intval(getGetOrPost('mid'));
        $data ['bid'] = intval(getGetOrPost('bid'));
        return $data;
    }

    /**
     * 获取商场楼层信息
     *
     * @author ice<iceinto@mallog.com.cn>
     */
    public function getFloors()
    {
        $status = 0;
        $floors = array();
        $mid = intval(getGet('id'));
        if ($mid) {
            $map = array();
            if ($this->_level == 1) {
                $floors = D('Mall')->getFloorList($mid, 'id,sain as name');
            } else if ($this->_level == 2 || $this->_level == 3) {
                $map['mid'] = $this->_mid;
                $map['fid'] = $this->_fid;
                $floors = D('Mall')->getFloorListByWhere($map, 'id,sain as name');
            }
            if ($floors) {
                $status = 1;
            }
        }
        $this->assign('floors', $floors);
        $this->ajaxReturn($this->fetch(), null, $status);
    }

    /**
     * 获取商场楼层品牌信息
     *
     * @author ice<iceinto@mallog.com.cn>
     */
    public function getBrands()
    {
        $brands = array();
        $status = 1;
        $fid = intval(getGet('id'));
        $TaskModel = D('Task');
        $QueueModel = D('Queue');
        $time = time();
        if ($this->_level == 1 || $this->_level == 2) {
            $brands = D('Mall')->getFloorBrandList($fid);
        } else if ($this->_level == 3) {
            $map = array();
            $map['bid'] = array('IN', $this->_bids);
            $brands = D('Mall')->getFloorBrandList($fid, $map);
        }
        if ($brands) {
            $status = 1;
            // Get brand task
            foreach ($brands as $key => $brand) {
                $activity = $TaskModel->getBrandLastActivity($brand ['mid'], $fid, $brand ['id']);
                $brands [$key] ['activity'] = $activity;
                if ($activity) {
                    if ($activity['status'] != 100 && $activity['status'] != 1) {
                        $brands[$key]['activity']['status'] = $QueueModel->getStatusById($activity['id']);
                    } else {
                        $brands[$key]['activity']['status'] = $activity['status'];
                    }
                    $brands [$key] ['activity'] ['status_info'] = $QueueModel->getStatus($brands [$key] ['activity'] ['status']);
                    $color = 'green';
                    if ($brands [$key] ['activity'] ['end_time'] < $time) {
                        $color = 'red';
                    }
                    $brands [$key] ['activity'] ['color'] = $color;
                }
            }
        }
        $this->assign('fid', $fid);
        $this->assign('brands', $brands);
        $this->ajaxReturn($this->fetch(), null, $status);
    }

    /**
     * 获取商场楼层品牌信息
     *
     * @author ice<iceinto@mallog.com.cn>
     */
    public function getMallTasks()
    {
        $brands = array();
        $status = 0;
        $mid = intval(getGet('id'));
        $tasks = D('Task')->getMallNowTasks($mid);
        if ($tasks) {
            $MallModel = D('Mall');
            $status = 1;
            foreach ($tasks as $key => $task) {
                $brands [$key] = $MallModel->getBrand($task ['bid']);
                $brands [$key] ['activity'] = $task;
            }
            $this->assign('brands', $brands);
        }
        $this->ajaxReturn($this->fetch(), null, $status);
    }

    /**
     * audit
     */
    public function audit()
    {
        if ($this->_level == 1) {
        } else {
            $this->errorLang('_NOT_ACCESS');
        }
        $this->display();
    }

    public function auditList()
    {
        $status = 0;
        $TaskModel = D('Task');
        $map['mid'] = $this->_mid;
        $map['status'] = 3;
        $tasks = $TaskModel->where($map)->limit('0,2')->select();
        if ($tasks) {
            $MallPhoneModel = D('MallPhone');
            $MallModel = D('Mall');
            $status = 1;
            foreach ($tasks as $key => $task) {
                $task = $MallModel->setAddress($task);
                $task['phones'] = $MallPhoneModel->getList($task['mid'], $task['fid']);
                $tasks[$key] = $task;
            }
            $this->assign('tasks', $tasks);
        }
        if ($status) {
            $this->ajaxReturn($this->fetch(), count($tasks), $status);
        } else {
            $this->ajaxReturn('没有需要审核的活动', null, $status);
        }

    }

    public function doAudit()
    {
        $status = 0;
        $message = '';
        $TaskModel = D('Task');
        $tid = intval(getGetOrPost('tid'));
        $task = $TaskModel->getById($tid);

        if ($task) {
            if ($task['status'] == 3) {
                $data = array();
                $data['status'] = 1;
                $data['id'] = $tid;
                if ($TaskModel->save($data)) {
                    unset($data);
                    $data['tid'] = $tid;
                    $data['uid'] = $this->getLoginUserInfo();
                    $data['audit_time'] = time();
                    M('mallTaskAudit')->add($data);
                    $status = 1;
                }
            } else {
                $message = '此活动不能审核';
            }
        } else {
            $message = '活动不存在';
        }
        $this->ajaxReturn($message, null, $status);
    }

    /**
     * 活动延期
     * @author ice<iceinto@mallog.com.cn>
     */
    public function activityExtension()
    {
        $this->AjaxHead();
        $status = 0;
        $message = '';
        $id = intval(getGetOrPost('id'));
        $task = D('Task')->find($id);
        $QueueModel = M('Queue');
        if ($task) {
            $queue = $QueueModel->find($id);
            if ($queue) {
                $message = '队列中还有对应处理没有结束，不能进行续期';
                $this->ajaxReturn($message, null, $status);
            }
        }
        if (isPost() && $task) {
            $endTime = getPost('end_time');
            if (!empty($endTime)) {
                $this->ajaxIsAuthorize($task['mid'], $task['fid'], $task['bid']);
                $data = array();
                $data['tid'] = $id;
                $data['uid'] = $this->getLoginUserInfo();
                $data['create_time'] = time();
                $data['end_time'] = strtotime($endTime);
                $data['status'] = 1;
                if ($task['start_time'] > $data['end_time']) {
                    $message = '结束时间不能小于开始时间';
                } else {
                    $ActivityExtensionModel = M('ActivityExtension');
                    $rs = $ActivityExtensionModel->add($data);
                    if ($rs) {
                        //添加队列
                        unset($data);
                        $data['tid'] = $id;
                        $data['creator'] = $this->getLoginUserInfo();
                        $data['mid'] = $task['mid'];
                        $data['fid'] = $task['fid'];
                        $data['bid'] = $task['bid'];
                        $data['status'] = 70; //等待续期任务
                        $data['create_time'] = time();
                        $rss = $QueueModel->add($data);
                        if (!$rss) {
                            $ActivityExtensionModel->delete($rs);
                            $message = '队列添加失败';
                        } else {
                            unset($data);
                            $data['id'] = $id;
                            $data['end_time'] = strtotime($endTime);
                            M('Task')->save($data);
                            $status = 1;
                        }
                    }
                }
            } else {
                $message = '结束时间必须';
            }
            //添加一个
        } else if ($task) {
            $status = 1;
            $this->assign('task', $task);
            $this->ajaxReturn($this->fetch(), null, $status);
        }
        $this->ajaxReturn($message, null, $status);
    }
}

?>